﻿using System;
using System.IO;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.LIB;
using YJKExcelFormTool.DataDefine;
using YJKExcelFormTool.Kits;

namespace YJKExcelFormTool.Designer
{
	public class GeneralTableOutputKit
	{
		public GeneralTableOutputKit(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
		}

		public Result Drawing(TableInfos tableInfos, ref string message, Autodesk.Revit.DB.View view = null, bool drag = true)
		{
			if (tableInfos == null)
			{
				message = "表格为空";
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (view == null && new ViewControler(this.m_Revit, ViewControler.TableViewType.TVT_GENERAL).CreateDraftingView(100) == ViewSelectResult.VSR_Cancel)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			TableDrawingToRevitKit tableDrawingToRevitKit = new TableDrawingToRevitKit(this.m_Revit, tableInfos, view);
			Result result;
			try
			{
				result = tableDrawingToRevitKit.Drawing(drag);
			}
			catch
			{
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		public Result Export(TableInfos tableInfos, ref string message)
		{
			if (tableInfos == null)
			{
				message = "表格为空";
				return Autodesk.Revit.UI.Result.Failed;
			}
			string name = tableInfos.Head.TableSourceInfo.Name;
			if (!File.Exists(name))
			{
				int num = name.LastIndexOf("\\");
				string fileName = name.Substring(num + 1, name.Length - (num + 1));
				tableInfos.Head.TableSourceInfo.Name = this.GetDefaultTemplateFile(fileName);
			}
			TableExportKit tableExportKit = new TableExportKit(tableInfos, true, default(TableExportKit.FontSetting));
			Transaction transaction = new Transaction(this.m_Revit.Application.ActiveUIDocument.Document);
			transaction.Start("Export table");
			try
			{
				tableExportKit.ExportToExcel();
				transaction.Commit();
			}
			catch
			{
				if (transaction != null)
				{
					transaction.RollBack();
				}
				message = "导出失败，请检查是否安装了Excel";
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private string GetDefaultTemplateFile(string fileName)
		{
			string text = Product.WorkingLocation + "General_" + fileName;
			if (!File.Exists(text))
			{
				string sourceFileName = AssistFunc.GetAppRootPath() + "\\Data\\" + fileName;
				this.CopyFile(sourceFileName, text);
			}
			return text;
		}

		private void CopyFile(string sourceFileName, string destFileName)
		{
			try
			{
				File.Copy(sourceFileName, destFileName);
			}
			catch (Exception)
			{
			}
		}

		private ExternalCommandData m_Revit;
	}
}
